package com.rcl.httpurlconnection.presenter;

import com.google.gson.Gson;
import com.rcl.httpurlconnection.bean.ItemBean;
import com.rcl.httpurlconnection.interfaces.IitemCallBackView;
import com.rcl.httpurlconnection.interfaces.IitemPresenter;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/*
 * class title:
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2020/10/22.
 * PS: Not easy to write code, please indicate.
 */
public class ItemPresenter implements IitemPresenter {

    private static ItemPresenter sItemPresenter;
    private List<IitemCallBackView> mIitemCallBackViewList = new ArrayList<>();

    private ItemPresenter() {
    }

    public synchronized static ItemPresenter getInstance() {
        if (sItemPresenter == null) {
            sItemPresenter = new ItemPresenter();
        }
        return sItemPresenter;
    }

    @Override
    public void getItemData() {
        try {
            URL url = new URL("https://gank.io/api/v2/banners");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(5000);
            urlConnection.connect();

            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String ling = bufferedReader.readLine();
                inputStream.close();
                Gson gson = new Gson();
                ItemBean itemBean = gson.fromJson(ling, ItemBean.class);
                loadData(itemBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadData(ItemBean itemBean) {
        if (itemBean != null) {
            for (IitemCallBackView iitemCallBackView : mIitemCallBackViewList) {
                iitemCallBackView.onItemData(itemBean.getData());
            }
        }
    }

    @Override
    public void registerCallBackView(IitemCallBackView callBackView) {
        if (callBackView != null) {
            if (!mIitemCallBackViewList.contains(callBackView)) {
                mIitemCallBackViewList.add(callBackView);
            }
        }
    }

    @Override
    public void unregisterCallBackView(IitemCallBackView callBackView) {
        if (callBackView != null) {
            mIitemCallBackViewList.remove(callBackView);
        }
    }
}
